<template>
  <div class="app-container">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="数据上传列表" name="first">
        <el-form :model="queryParams_data" ref="queryForm_data" size="small" :inline="true" v-show="showSearch_data" label-width="68px">
            <el-form-item label="数据名称" prop="dataName" >
              <el-input
                v-model="queryParams_data.dataName"
                placeholder="请输入数据名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery_data"
              />
            </el-form-item>
            <el-form-item label="备注"  prop="remark">
              <el-input
                v-model="queryParams_data.remark"
                placeholder="请输入备注"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery_data"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams_data.status"
                placeholder="状态"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery_data"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange_data"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery_data"
                        v-hasPermi="['system:dataFile:list']">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery_data"
                         v-hasPermi="['system:dataFile:list']">重置</el-button>
            </el-form-item>
          </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="clickUpload"
                v-hasPermi="['system:dataFile:add']"
              >新增</el-button>
            </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery_data"
              v-hasPermi="['system:dataFile:list']"
            >刷新缓存</el-button>
          </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="handleDelete_many"
                v-hasPermi="['system:dataFile:remove']"
              >删除</el-button>
            </el-col>

            <right-toolbar :showSearch.sync="showSearch_data" @queryTable="resetQuery_data"></right-toolbar>
          </el-row>

        <el-table v-loading="loading_data" :data="dataList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50px" align="center" />
            <el-table-column label="数据编号" align="center" prop="id" width="100px" />
            <el-table-column label="数据名称" align="center" prop="dataName" :show-overflow-tooltip="true" width="150px"/>
            <el-table-column label="标准号" align="center" prop="standardCode" :show-overflow-tooltip="true" width="150px"/>
            <el-table-column label="状态" align="center" prop="status" width="150px">
              <template slot-scope="scope">
                <el-tag :type="statusTagMap[scope.row.status]">{{ statusMap[scope.row.status] }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            </el-table-column>
            <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate_data(scope.row)"
                  v-hasPermi="['system:dataFile:edit']"
                >修改</el-button>

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-download"
                  @click="handleDownload(scope.row)"
                  v-hasPermi="['system:dataFile:download']"
                >下载</el-button>

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-time"
                  @click="handlePath(scope.row)"
                  v-hasPermi="['system:dataFile:trace']"
                >跟踪</el-button>

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-operation"
                  @click="handleCheck(scope.row)"
                  v-hasPermi="['system:dataFile:audit']"
                >审核</el-button>

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row,'single')"
                  v-hasPermi="['system:dataFile:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
        </el-table>

        <pagination
          v-show="dataTotal>0"
          :total="dataTotal"
          :page.sync="queryParams_data.pageNum"
          :limit.sync="queryParams_data.pageSize"
          @pagination="queryDataList"
          />


        <!-- 修改数据- Excel ---------------------------->
        <el-dialog title="修改数据(指标得分Excel)" :visible.sync="updateDataDialog.visible_excel" width="500px">
          <el-form label-width="80px" label-position="left">
            <el-form-item label="修改备注: " v-if="updateDataDialog.row && updateDataDialog.row.remark !== undefined">
              <el-input v-model="updateDataDialog.row.remark" :placeholder="'请输入备注'" style="text-align: left;"></el-input>
            </el-form-item>
          </el-form>

          <update-excel :title="getExcelFileName()" :upload-data="this.updateDataDialog.data_excel" :can-upload="true"></update-excel>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="refreshUpdateDataFile('excel')"  >刷新 数据</el-button>
          </span>
        </el-dialog>

        <!-- 修改数据- 补充性文件supplement ---------------------------->
        <el-dialog title="修改数据(补充性文件)" :visible.sync="updateDataDialog.visible_supplement" >
          <el-form label-width="120px">
            <el-form-item label="说明">
          <span>
            <strong>数据名称:</strong> {{ updateDataDialog.data_supplement.dataName }}
            <span class="spacer"></span>
            <strong>标准号:</strong> {{ updateDataDialog.data_supplement.standardCode }}
          </span>
            </el-form-item>
            <div style="max-height: 500px;  overflow-y: auto; overflow-x: auto"  >
              <el-form-item label="备注" v-if="updateDataDialog.row && updateDataDialog.row.remark !== undefined">
                <el-input v-model="updateDataDialog.row.remark" :placeholder="'请输入备注'" style="text-align: left;"></el-input>
              </el-form-item>

              <el-form-item v-for="(urlList, key) in updateDataDialog.data_supplement.filesPath" :key="key" :label="key">
                <el-row >
                  <el-col :span="6" v-for="(url,index) in urlList" :key="index">
                    <update-supplement :can-upload="true" :title="getSupplementName(url)" :upload-data="{dataName:updateDataDialog.data_supplement.dataName,previousUrl:url,indicator:key}">
                    </update-supplement>
                  </el-col>
                </el-row>
              </el-form-item>
            </div>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="refreshUpdateDataFile('supplement')" >刷新 数据</el-button>
          </span>
        </el-dialog>


        <!-- 上传数据 ---------------------------->
        <el-dialog title="上传数据" :visible.sync="UD_dialog.visible" width="50%">
          <el-form label-width="120px">
            <el-form-item label="数据类型">
              <el-select v-model="UD_dialog.selectedType" placeholder="请选择数据类型" size="large" style="width: 240px" @change="UD_selectType" clearable>
                <el-option v-for="item in UD_dialog.dataType" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
            <!-- 通用填写  dataName,remark -->
            <el-form-item v-if="UD_dialog.selectedType" v-for="field in UD_dialog.newInputs" :key="field" :label="UD_dialog.dataMap[field]">
              <el-input v-if="UD_dialog.data.hasOwnProperty(field)" v-model="UD_dialog.data[field]" :disabled="UD_dialog.uploadExcelVisible||UD_dialog.uploadSupplementVisible"    placeholder="请输入内容"/>
            </el-form-item>

            <!-- 数据类型为  标准excel时-->
            <el-form-item v-if="UD_dialog.selectedType=== '标准Excel文件'" label="下载模板">
              <el-button type="small" @click="UD_downloadExcelTemplate">下载模板</el-button>
            </el-form-item>
            <el-form-item v-if="UD_dialog.selectedType === '标准Excel文件'" label="文件" prop="file">
              <el-button v-if="!UD_dialog.uploadExcelVisible" @click="UD_excelUpload" size="mini" type="success">新增(确定参数)</el-button>
              <upload-excel  v-if="UD_dialog.uploadExcelVisible" :upload-data="UD_dialog.getUploadData('excel')"></upload-excel>
            </el-form-item>

            <!-- 数据类型为  指标补充文件时-->
            <!-- 选择标准号-->
            <el-form-item v-if="UD_dialog.selectedType==='指标补充文件'" label="标准号">
              <el-select v-model="UD_dialog.data['standardCode']" placeholder="请选择标准号" :disabled="UD_dialog.uploadSupplementVisible"  size="large" style="width: 240px" clearable
                         filterable :remote="true" :remote-method="filterStandardCode" :loading="UD_dialog.loadingFilter">
                <el-option v-for="item in UD_dialog.filteredCodes" :key="item" :label="item" :value="item"/>
              </el-select>
            </el-form-item>
            <!-- 新增补充文件-->
            <el-form-item v-if="UD_dialog.selectedType==='指标补充文件'" label="新增补充文件" >
              <el-button size="small" type="success" icon="el-icon-plus"  @click="UD_supplementUpload">确定参数</el-button>
              <!-- 填写完相应信息后展示 上传 -->
              <el-form-item v-if="UD_dialog.uploadSupplementVisible">
                <div style="max-height: 300px;  overflow-y: auto;" >
                  <el-row v-for="(row, index) in this.UD_dialog.supplementRows" :key="index">
                    <el-col :span="8">
                      <strong >指标:</strong>
                      <el-form-item>
                        <el-select v-model="row.indicator" placeholder="请选择指标" size="large" style="width: 120px" clearable>
                          <el-option v-for="item in UD_dialog.indicatorList" :key="item" :label="item" :value="item"/>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="16">
                      <strong>选择并上传补充性文件:</strong>
                      <upload-supplement v-if="row.indicator" :upload-data="UD_dialog.getUploadData(row.indicator)"> 选择文件并上传</upload-supplement>
                    </el-col>
                  </el-row>
                </div>
              </el-form-item>
            </el-form-item>


          </el-form>
          <span slot="footer" class="dialog-footer">
      <el-button @click="UD_cancel">取 消</el-button>
      <el-button type="primary" @click="UD_refresh">刷新 数据</el-button>
    </span>
        </el-dialog>

        <!-- 下载数据 ---------------------------->
        <el-dialog title="下载数据" :visible.sync="DL_dialog.visible" >
          <el-form label-width="120px">
            <el-form-item label="说明">
          <span>
            <strong>数据名称:</strong> {{ DL_dialog.data.dataName }}
            <span class="spacer"></span>
            <strong>标准号:</strong> {{ DL_dialog.data.standardCode }}
          </span>
            </el-form-item>
            <div style="max-height: 500px;  overflow-y: auto; overflow-x: auto"  >
              <el-form-item v-for="(urlList, key) in DL_dialog.data.filesPath" :key="key" :label="key">
                <el-row >
                  <el-col :span="6" v-for="(url,index) in urlList" :key="index">
                    <el-button size="mini" type="text" icon="el-icon-download" @click="DL_downloadFile(url)" :title="getSupplementName(url)">
                        <span style="display: inline-block; width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ getSupplementName(url) }}
                      </span>
                    </el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </div>
          </el-form>
        </el-dialog>

        <!-- 数据跟踪 ---------------------------->
        <el-dialog title="数据跟踪" :visible.sync="historyVisible">
          <div>
            <el-timeline>
              <el-timeline-item
                v-for="item in logHistoryList"
                :key="item.id"
                :timestamp="parseTime(item.oper_time)"
                placement="top"
                :color="activeId !== item.id ? '' : '#0bbd87'"
                :id="item.id"
              >
                <el-card style="width: 100%">
                  <div
                    slot="header"
                    class="clearfix flex jc-between ai-center"
                    style="width: 100%"
                  >
                    <div style="flex:1">{{ item.oper_user }} {{item.oper_type}} {{item.data_name}}</div>
                  </div>
                  <div v-for="(value, key) in item.content" :key="key" class="mb-1">
                    <p><strong>{{ key }}:</strong></p>
                    <p>
                      <el-tag type="info">{{ value.before || '-' }}</el-tag>
                      <span class="el-icon-arrow-right" />
                      <el-tag type="success">{{ value.after || '-' }}</el-tag>
                    </p>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
            <template v-if="!this.logHistoryList.length">
              <el-empty />
            </template>
          </div>
        </el-dialog>

        <!-- 审核数据 ---------------------------->
        <el-dialog title="审核数据" :visible.sync="checkReview.visible" >
          <el-form
            ref="form"
            :model="checkReview"
            label-width="80px"
            size="large"
            :rules="rules"
          >
            <el-form-item label="审核" prop="status">
              <el-radio-group v-model="checkReview.status">
                <el-radio :label="0" >通过</el-radio>
                <el-radio :label="1" >不通过</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="checkReview.remark"
                clearable
                type="textarea"
                maxlength="100"
                show-word-limit
                placeholder="`请填写备注"
              />
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
        <el-button @click="checkReview.visible = false" >取 消</el-button>
        <el-button type="primary" @click="submitCheckReview" >确 定</el-button>
      </span>
        </el-dialog>


      </el-tab-pane>

      <!------------------------------------------------------------------------------------------------------------->
      <!------------------------------------------------------------------------------------------------------------->
      <!------------------------------------------------------------------------------------------------------------->
      <!------------------------------------------------------------------------------------------------------------->
      <el-tab-pane label="标准评价数据" name="second">
        <el-form :model="queryParams_standard" ref="queryForm_standard" size="small" :inline="true" v-show="showSearch_standard" label-width="68px">
          <el-form-item label="标准号" prop="standardCode">
            <el-input
              v-model="queryParams_standard.standardCode"
              placeholder="请输入标准号"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery_standard"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="queryParams_standard.remark"
              placeholder="请输入备注"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery_standard"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange_standard"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery_standard"
                      v-hasPermi="['system:standard:query']">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery_standard"
                       v-hasPermi="['system:standard:query']">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading_standard" :data="standardList" >
<!--          @selection-change="handleSelectionChange"-->
<!--          type="selection"-->
          <el-table-column  width="55" align="center" />
          <el-table-column label="序号" align="center" prop="id" width="100" />
          <el-table-column label="标准号" align="center" prop="standardCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-link style="color: #2b2f3a;text-decoration-color: #222222"  type="primary" @click="moveToStandardManager(scope.row)">{{ scope.row.standardCode }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" align="center" prop="createTime" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate_indicator(scope.row)"
                v-hasPermi="['system:standard:edit_original']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-search"
                @click="beforeHandleView(scope.row)"
                v-hasPermi="['system:standard:view_2type']"
              >查看</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete_standard(scope.row)"
                v-hasPermi="['system:standard:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="standardTotal>0"
          :total="standardTotal"
          :page.sync="queryParams_standard.pageNum"
          :limit.sync="queryParams_standard.pageSize"
          @pagination="queryStandardList"
        />


        <!-- 选择查看对象对话框 -->
        <el-dialog title="选择要查看的对象" :visible.sync="BS_params.viewDialogVisible" width="400px">
          <el-row>
            <el-col span="24">
<!--              <el-button size="medium" type="success" @click="handleView_standard(BS_params.row)">查看标准</el-button>-->
              <el-button size="medium" type="primary" @click="handleView_indicator(BS_params.row)"
                        v-hasPermi="['system:standard:view_original']">查看标准原始数据得分</el-button>
              <el-button size="medium" type="warning" @click="viewSupplementFiles(BS_params.row)"
                        v-hasPermi="['system:standard:view_files']">查看补充文件</el-button>
            </el-col>
          </el-row>
        </el-dialog>

        <!-- 查看标准的补充性文件 -->
        <el-dialog title="查看标准的补充性文件" :visible.sync="BS_params.supplementFilesVisible" >
          <el-form label-width="120px">
            <el-form-item label="说明">
                <strong>标准号   </strong> {{ BS_params.standardCode }}
            </el-form-item>
            <el-form-item label="补充文件" style="max-height: 400px;  overflow-y: auto; overflow-x: auto">
              <template v-if="Object.keys(BS_params.filesPath).length > 0">
              <div v-for="(urlList, indicator) in BS_params.filesPath" :key="indicator" style="max-height: 100px;  overflow-y: auto; overflow-x: auto"  >
                <strong>指标 {{ indicator }}   </strong>
                <div >
                  <el-row >
                    <el-col :span="6" v-for="(url, index) in urlList" :key="index">
                      <el-button size="mini" type="text" icon="el-icon-download" @click="DL_downloadFile(url)" :title="getSupplementName(url)">
                        <span style="display: inline-block; width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ getSupplementName(url) }}
                      </span>
                      </el-button>
                      <span v-if="index < urlList.length - 1">, </span>
                    </el-col>
                  </el-row>
                </div>
              </div>
              </template>

              <template v-else>
                <span>暂无数据</span>
              </template>
            </el-form-item>

          </el-form>
        </el-dialog>


        <!-- new  --修改对话框 -- 修改标准原始数据得分-->
        <el-dialog title="修改标准原始数据得分" :visible.sync="indicatorVisible_edit">
          <el-form :model="excel_to_show" label-width="300px" label-position="left">
            <el-form-item v-for="(value, key) in excel_to_show" :key="key" :label="excelMap[key]" v-if="key!=='id'" style="margin-bottom: 10px">
              <el-input v-model="excel_to_show[key]" :disabled="key==='standardCode'||key==='id'" style="width: 200px;"></el-input>

              <!-- 添加 desc 显示 -->
              <el-input :value="getMatchedDesc(key) || ''" disabled style="width: 200px; margin-top: 5px;"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="indicatorVisible_edit= false">取 消</el-button>
            <el-button type="primary" @click="confirmUpdate_indicator" v-hasPermi="['system:standard:edit_indicator']">确 定</el-button>
          </div>
        </el-dialog>

        <!-- new --查看对话框  查看标准指标的得分信息-->
        <el-dialog title="查看标准原始数据得分" :visible.sync="indicatorVisible_query">
          <el-table :data="Object.entries(excel_to_show).filter(([key]) => key !== 'id')" border style="width: 100%;" :show-header="false">
            <el-table-column prop="0" label="Key" width="200">
              <template slot-scope="scope">
                {{ excelMap[scope.row[0]] }}
              </template>
            </el-table-column>
            <el-table-column prop="1" label="Value">
              <template slot-scope="scope">
                {{ scope.row[1]}}
              </template>
            </el-table-column>

            <el-table-column label="Description" width="300">
              <template slot-scope="scope">
                <!-- 获取前3个字母 -->
                <span>
                    {{ getMatchedDesc(scope.row[0]) || '' }}
                </span>
              </template>
            </el-table-column>

          </el-table>

        </el-dialog>


      </el-tab-pane>


    </el-tabs>


  </div>
</template>

<script>
import { listMenu, getMenu, delMenu, addMenu, updateMenu } from "@/api/system/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import {
  getStandardExcelByStandardCode,
  getStandardDetailByCode,
  listStandard,
  updateStandardDetailByCode,
  updateExcelByStandardCode,
  deleteStandardByCode,
  getAllStandardCode,
  addStandardBase,
  addStandardISO, addStandardIEC,
} from "@/api/standard/standard";
import {
  auditDataFileStatus, delDataFile, delDataFileById, deleteDataOperLogByDataName,
  getAllDataFile,
  getDataFileInfo, getDataFileInfoByName,
  getListDataFile,
  getLogData,
  insertLogData, mergeFilesPath, updateDataFileRemark
} from "@/api/standard/dataFile";
import {MessageBox} from "element-ui";
import axios from "axios";
import {getToken} from "@/utils/auth";
import {getIndicatorName_DescMap} from "@/api/indicator/indicator";

const statusMap = {
  0: "审核通过",
  1: "未通过审核",
  2: "待审核"
};

const statusTagMap = {
  0: "success",
  1: "danger",
  2: "warning"
};

const labelMap={
  'id':'标准编号',
  'standardCode':'标准号',
  'standardName':'标准名称',
  'classificationCode':'国际分类号',
  'organization':'制定组织',
  'remark':'备注',

  'title':'标题',
  'content':'内容主题',
  'part':'分部分号和名称(part)',
  'abstract_':'摘要(abstract)',
  'status':'状态',
  'publicationType':'发布类型',
  'publicationDate':'发布日期',
  'availableLanguages':'支持语言',
  'stage':'所处阶段(stage)',
  'edition':'版本号',
  'numberOfPages':'页数',
  'pages':'页数',
  'technicalCommittee':'技术委员会',
  'ics':'国际标准分类号(ICS)',
  'contribute':'贡献记录',
  'TC_SC':'技术委员会/子委员会(TC/SC)',
  'tc_SC':'技术委员会/子委员会(TC/SC)',
  'ICS':'国际标准分类号(ICS)',
  'relatedPublications':'相关出版物',
};

// 不可修改字段
const cannotEdit=['id','standardCode','status','createTime'];

/**
 * 以标准为中心---excel
 */
const excelMap={
  'id':'编号',
  'standardCode':'标准号',
  'a11':'A11(参与国家影响力)',
  'a12':'A12(参与企业/组织影响力)',
  'a13':'A13(起草人员)',
  'b11':'B11(标准转化)',
  'b12':'B12(其他标准引用)',
  'b13':'B13(被法律法规引用)',
  'b14':'B14(其他工程应用)',
  'b21':'B21(标准传播)',
  'b22':'B22(认证认可)',
  'b23':'B23(标准关注度)',
  'b24':'B24(标准衍生材料传播)',
  'b31':'B31(标准引领性)',
  'b32':'B32(标准创新性)',
  'b33':'B33(标准获奖)',
  'b41':'B41(社会关注度)',
  'b42':'B42(可持续发展支撑度)',
  'b43':'B43(对外贸易应用(国际贸易影响))',
  'b44':'B44(产业扩散广度)',
}


export default {
  name: "datamanager",
  dicts: ['sys_show_hide', 'sys_normal_disable'],
  components: { Treeselect, IconSelect },
  data() {
    return {
      /** name:Desc 的map*/
      indicatorName_Desc_Map:{},
      /**
       * 修改对话框参数
       */
      updateDataDialog:{
        row:null,

        visible_excel:false,
        data_excel:{
          previousUrl:'',
          dataName:'',
        },

        visible_supplement:false,
        data_supplement:{
          dataName:'',
          standardCode:'',
          filesPath:{},
        },
      },

      /** 选中行 */
      selectedRows: [],
      /** 新增标准相关参数 */
      addNewStandard:{
        baseDialogVisible:false,
        ISODialogVisible:false,
        IECDialogVisible:false,
        // 可选组织
        organizationType:['ISO','IEC'],
        // 标准开头格式
        codeList:["ISO","IEC"],

        baseInfo:{
          standardCode:'',
          standardName:'',
          classificationCode:'',
          organization:'',
          remark:'',
        },
        ISO:{
          standardCode:'',
          title:'',
          content:'',
          part:'',
          abstract_:'',
          status:'',
          publicationDate:'',
          stage:'',
          edition:'',
          numberOfPages:'',
          technicalCommittee:'',
          ics:'',
          contribute:'',//JSON 格式需要转换
        },
        IEC:{
          standardCode:'',
          title:'',
          abstract_: '',
          publicationType:'',
          publicationDate: '',
          edition:'',
          availableLanguages:'',
          TC_SC: '',
          ICS:'',
          pages:'',
          relatedPublications:'',// JSON 格式需要转换
        },
      },

      /**
       * 以标准为中心 --- 相关参数
       */
      BS_params:{
        row:null,
        updateDialogVisible:false,
        viewDialogVisible:false,

        /**
         * 标准: 指标 (1:n)
         * 指标: 文件 (1:n)
         */
        supplementFilesVisible:false,
        standardCode:'', // 标准号
        filesPath:{// 存 指标: 多个补充文件路径 的映射关系
        }
      },

      /**
       * 上传数据对话框
       */
      UD_dialog:{
        loadingFilter:false,
        filteredCodes:[],

        visible:false,
        // 数据类型
        dataType:[{value: '标准Excel文件', label: '标准Excel文件',},
          {value: '指标补充文件', label: '指标补充文件',},],

        newInputs:[],
        // 英译中
        dataMap:{
          'dataName':'数据名称',
          'remark':'备注',
          'standardCode':'标准号',
          'indicator':'指标',
        },
        // 选择的数据类型
        selectedType:'',
        // 存储写的input内容
        data:{
          'dataName':'',
          'remark':'',
          'standardCode':'',
          'indicator':'',
        },
        uploadData:{
          dataType:'',
          dataName:'',
          remark:'',
          standardCode:'',
          indicator:'',
        },
        getUploadData(indicator){
          this.uploadData.dataType=this.selectedType;
          this.uploadData.dataName=this.data['dataName'];
          this.uploadData.remark=this.data['remark'];
          this.uploadData.standardCode=this.data['standardCode'];
          this.uploadData.indicator=indicator;
          return this.uploadData;
        },
        // Excel 相关参数
        excelForm:{
          excelFile:null,
        },
        uploadExcelVisible:false,
        uploadSupplementVisible:false,

        /**
         * 所有标准号
         */
        standardCodeList:[],
        /**所有指标*/
        indicatorList:['A11','A12','A13',
          'B11','B12','B13','B14',
          'B21','B22','B23','B24',
          'B31','B32','B33',
          'B41','B42','B43','B44',],
        /**多个补充性文件(rows)*/
        supplementRows:[],
        /** 是否在一次上传过程中？*/
        isUploadingExcel:false,
        isUploadingSupplement:false,
      },
      /**
       * 下载对话框
       * 这里默认是对 dataType=supplement 的数据进行记录的
       */
      DL_dialog:{
        visible:false,
        data:{
          dataName:'',
          standardCode:'',
          filesPath:{},// 记录 {指标:文件路径} 的映射关系
        },

      },

      /** 数据跟踪参数 */
      historyVisible: false,
      logHistoryList: [],

      statusMap,
      statusTagMap,
      /**
       * new -----------------
       */
      labelMap,
      cannotEdit,
      excelMap,


      // 查看 指定标准字段信息
      detailVisible_query: false,
      data_to_show: {},

      // 编辑/修改 指定标准字段信息
      detailVisible_edit: false,
      standardCode_to_edit: '',
      data_to_edit: {},

      // 跟踪 数据操作日志
      oper_type: '',
      data_name: '',
      log_before: {},
      log_after: {},

      // 审核对话框
      checkReview: {
        row: "",
        visible: false,
        status: 1,
        remark: ""
      },

      // 标准excel信息(原始数据得分)
      excel_to_show: {},

      /** 查询时的相关参数 */
      /** 查询----------数据*/
      dataList:[],
      loading_data: true,
      showSearch_data: true,
      dataTotal: 0,
      dateRange_data: [],
      queryParams_data: {
        pageNum: 1,
        pageSize: 10,
        dataName:undefined,
        remark:undefined,
        status:undefined,
      },
      /** 查询 --------- 标准*/
      standardList:[],
      loading_standard: true,
      showSearch_standard: true,
      standardTotal: 0,
      dateRange_standard: [],

      queryParams_standard: {
        pageNum: 1,
        pageSize: 10,
        standardCode:undefined,
        remark:undefined,
      },

      // tab
      activeName :'first',
      /**  下方 参数使用情况不明*/
      value:null,
      // 遮罩层

      // 显示搜索条件

      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 新增数据字段
      addDataFields: [],
      // 新增对话框显示状态，默认为false
      isAddDialogOpen: false,
      // 修改对话框显示状态，默认为false
      isUpdateDialogOpen: false,
      // 查看对话框显示状态，默认为false
      isViewDialogOpen: false,
      // 跟踪对话框显示状态，默认为false
      isPathDialogOpen: false,
      // 新增对话框显示状态，默认为false
      isAddDialogOpen2: false,
      // 修改对话框显示状态，默认为false
      indicatorVisible_edit: false,
      // 查看对话框显示状态，默认为false
      indicatorVisible_query: false,
      // 跟踪对话框显示状态，默认为false
      isPathDialogOpen2: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      //时间线数据
      timelineData: [
        { timestamp: '2015-09-01', content: '创建 by 用户1' },
        { timestamp: '2015-09-02', content: '修改 by 用户2' },
        { timestamp: '2015-09-03', content: '修改 by 用户3' },
        { timestamp: '2015-09-04', content: '修改 by 用户4' },
        { timestamp: '2015-09-05', content: '修改 by 用户5' },
        { timestamp: '2015-09-06', content: '修改 by 用户6' },
        // ...更多数据
      ],
      timelineData2: [
      { timestamp: '2015-09-01', content: '增加数据1 by 用户1' },
      { timestamp: '2015-09-02', content: '修改数据2 by 用户2' },
      { timestamp: '2015-09-03', content: '修改数据1 by 用户3' },
      { timestamp: '2015-09-04', content: '修改数据2 by 用户4' },
      { timestamp: '2015-09-05', content: '修改数据3 by 用户5' },
      { timestamp: '2015-09-06', content: '删除数据3 by 用户6' },
      ],
      // 查询参数

      // 表单参数
      form: {},
      //搜索的状态下拉框
      statusOptions : [
        {
          value: 0,
          label: '审核通过',
        },
        {
          value: 1,
          label: '未通过审核',
        },
        {
          value: 2,
          label: '待审核',
        },
      ],
      //选择数据类型的下拉框
      typeOptions : [
        {
          value: '标准文件',
          label: '标准文件',
        },
        {
          value: '补充文件',
          label: '补充文件',
        },
      ],
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" }
        ]
      },
      dataList2:[
        {
          id:'1',
          standardCode: '指标1',
          accessResult:'92',
        },
        {
          id:'2',
          standardCode: '指标2',
          accessResult:'92',
        },
        {
          id:'3',
          standardCode: '指标3',
          accessResult:'92',
        },
        {
          id:'4',
          standardCode: '指标4',
          accessResult:'92',
        },
        {
          id:'5',
          standardCode: '指标5',
          accessResult:'92',
        },
      ],
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        // headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/talkrecord/importAllRecords"//文件上传路径
      },

    };
  },
  created() {
    this.queryDataList();
    this.getIndicator_Name_Desc_Map();
  },

  methods: {
    /** ----------------------------------------- 通用操作 ----------------------------------
     */
    /** new - 点击切换tab */
    handleClick(tab) {
      this.activeName = tab.name;
      if(this.activeName === 'first') {
        // this.resetQuery_data();
        this.queryDataList();
      }
      if(this.activeName === 'second') {
        this.queryStandardList();
      }
    },
    /**  选中行  */
    handleSelectionChange(selection){
      this.selectedRows=selection;
    },


    /**
     * ------------------------------------------   以数据为中心 ----------------------------------
     */
    /**
     *  查询 及 更新相关 ---------------------
     */
    // 重置按钮 ---- 重置表单+查
    resetQuery_data() {
      this.dateRange_data = [];
      this.resetForm("queryForm_data");
      this.handleQuery_data();
    },
    // 条件查询---- 从第一页开始
    handleQuery_data() {
      this.queryParams_data.pageNum = 1;
      this.queryDataList();
    },
    queryDataList(){
      this.loading_data = true;
      getListDataFile(this.addDateRange(this.queryParams_data, this.dateRange_data)).then(response => {
        this.dataList = response.rows;
        this.dataTotal = response.total;
        this.loading_data = false;
      });
    },


    /**
     *  数据上传相关 ----------------------------
     */
    filterStandardCode(query){
      if (query !== '') {
        this.UD_dialog.loadingFilter = true;
        setTimeout(() => {
          this.UD_dialog.filteredCodes = this.UD_dialog.standardCodeList.filter(code => {
            return code.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
          this.UD_dialog.loadingFilter = false;
        }, 200);
      } else {
        this.UD_dialog.filteredCodes = this.UD_dialog.standardCodeList
      }
    },
    //  文件上传
    clickUpload(){
      this.UD_dialog.visible=true;
    },
    // 文件提交处理 默认已经提交了，这里就是刷新
    UD_refresh() {
      this.UD_cancel();
      this.queryDataList();
    },
    // 取消上传
    UD_cancel(){
      this.UD_dialog.visible = false;
      this.UD_selectType('');
    },
    //  获取所有标准号
    async getStandardCodeList(){
      try {
        const response = await getAllStandardCode();
        if (response.code === 200) {
          const list=[];
          for(let i=0;i<response.data.length;i++){
            list.push(response.data[i]);
          }
          this.UD_dialog.standardCodeList=list;
          this.UD_dialog.filteredCodes=list;
        } else {
          this.$message.error('获取标准号失败');
        }
      } catch (error) {
        this.$message.error('获取标准号失败');
      }
    },

    // 判断数据名称是否可行
    async UD_dataNameOK(dataName){
      const jsonData = JSON.stringify({dataName:dataName});
      const response = await getDataFileInfoByName(jsonData);
      if (response.code === 200) {
        if (response.data) {// 已经存在，冲突
          return false;
        } else {
          return true;
        }
      } else {
        this.$message.error('获取数据信息失败');
      }
    },

    // 上传 supplement 文件
    async UD_supplementUpload(){
      if (!this.UD_dialog.data['dataName'] ) {
        this.$message.warning('请填写数据名称');
        return;
      }
      if(!this.UD_dialog.isUploadingSupplement){// 上传前的参数判断
        this.UD_dialog.isUploadingSupplement=true;// 在上传，允许多个补充性文件
        const nameIsOk = await this.UD_dataNameOK(this.UD_dialog.data['dataName']);
        if(!nameIsOk){
          this.$message.warning('数据名称已存在，请修改');
          return;
        }
      }
      if(!this.UD_dialog.data['remark']){
        this.$message.warning('请填写备注');
        return;
      }
      if(!this.UD_dialog.data['standardCode'])
      {
        this.$message.warning('请填写标准号');
        return;
      }
      this.UD_dialog.uploadSupplementVisible=true;
      /**  添加新的一行  {指标:文件}*/
      this.UD_dialog.supplementRows.push({
        indicator:'',
      });
    },

    // 上传 excel 文件
    async UD_excelUpload(){
      if (!this.UD_dialog.data['dataName'] ) {
        this.$message.warning('请填写数据名称');
        return;
      }
      const nameIsOk = await this.UD_dataNameOK(this.UD_dialog.data['dataName']);
      if(!nameIsOk){
        this.$message.warning('数据名称已存在，请修改');
        return;
      }
      if(!this.UD_dialog.data['remark']){
        this.$message.warning('请填写备注');
        return;
      }
      this.UD_dialog.uploadExcelVisible=true;
    },

    // 选择 数据类型
    async UD_selectType(val){
      this.UD_dialog.isUploadingSupplement=false;
      this.UD_dialog.supplementRows=[];

      this.UD_dialog.isUploadingExcel=false;

      this.UD_dialog.selectedType=val;
      this.UD_dialog.uploadExcelVisible=false;
      this.UD_dialog.uploadSupplementVisible=false;
      this.UD_dialog.data={
        'dataName':'',
        'remark':'',
        'standardCode':'',
        'indicator':'',
      };
      if(val==='标准Excel文件') {
        this.UD_dialog.newInputs = ['dataName', 'remark'];
      } else if(val==='指标补充文件'){
        this.UD_dialog.newInputs = ['dataName', 'remark'];
        /**
         * 获取所有标准号
         */
        await this.getStandardCodeList();
      }else if(val===''){
        this.UD_dialog.newInputs=[];
      }

    },

    /**
     *  每行按钮操作---------------------------
     */
    /** 修改---刷新*/
    refreshUpdateDataFile(type){
      /**
       * 新增 API 实现修改备注
       */
      const id = this.updateDataDialog.row.id;
      const remark = this.updateDataDialog.row.remark;

      updateDataFileRemark(id,remark).then(response=>{
        if(response.code===200){
          this.$message.success('更新成功');
          /** 更新查询*/
          this.queryDataList();
          if(type==='excel'){
            this.updateDataDialog.visible_excel=false;
          }else if(type==='supplement'){
            this.updateDataDialog.visible_supplement=false;
          }
        }else{
          this.$message.error('备注更新失败');
        }
      }).catch(error=>{
        this.$message.error('备注更新失败',error);
      })

    },

    /** 修改 */
    async handleUpdate_data(row){
      this.updateDataDialog.row=row;
      if(row.dataType==='excel'){
        this.updateDataDialog.visible_excel=true;
        this.updateDataDialog.data_excel.previousUrl=this.updateDataDialog.row.excelPath;
        this.updateDataDialog.data_excel.dataName=this.updateDataDialog.row.dataName;
      }else if(row.dataType==='supplement'){
        await this.getSupplementInfo(row);
      }
    },
    // 获取数据信息 --- supplement
    async getSupplementInfo(row) {
      try {
        const response = await getDataFileInfo(row.id);
        if (response.code === 200) {
          const data = response.data;// 获取的数据
          this.updateDataDialog.data_supplement.dataName = data.dataName;
          this.updateDataDialog.data_supplement.standardCode = data.standardCode;
          this.updateDataDialog.data_supplement.filesPath = JSON.parse(data.filesPath);
          this.updateDataDialog.visible_supplement=true;
        }
        else {
          this.$message.error('获取数据信息失败');
        }
      } catch (error) {
        this.$message.error('获取数据信息失败');
      }
    },
    /** 下载*/

    getExcelFileName(){
      const url = this.updateDataDialog.data_excel.previousUrl;
      return url.substring(url.lastIndexOf('/') + 1);
    },
    /** 获取 补充性文件名称  */
    getSupplementName(url){
      /** 获取文件名 */
      return url.substring(url.lastIndexOf('/') + 1);
    },
    // 这里要判断 数据是 excel / supplement
    async handleDownload(row) {
      try {
        const response = await getDataFileInfo(row.id);
        if (response.code === 200) {
          const data = response.data;// 获取的数据
          if (data.dataType === 'excel') {// excel类型时，直接返回下载数据即可
            const url = data.excelPath;
            this.$download.resource(url, false);
          } else if (data.dataType === 'supplement') {
            this.DL_dialog.data.dataName = data.dataName;
            this.DL_dialog.data.standardCode = data.standardCode;
            this.DL_dialog.data.filesPath = JSON.parse(data.filesPath);
            this.DL_dialog.visible = true;
          }
        } else {
          this.$message.error('下载失败');
        }
      } catch (error) {
        this.$message.error('下载失败');
      }
    },
    // 下载excel类型的数据
    DL_downloadFile(url){
      this.$download.resource(url, false);
    },
    // 下载Excel 模板
    UD_downloadExcelTemplate(){
      const url = 'https://localhost:8080/profile/upload/standard_excel_template.xlsx';
      this.$download.resource(url, false);
    },

    /** 跟踪*/
    handlePath(row){
      getLogData(row.dataName).then(response=>{
        if(response.code===200){
          this.logHistoryList=response.data.map((item)=>({
            id:item.id,
            oper_type:item.operType,
            data_name:item.dataName,
            content:JSON.parse(item.content),
            oper_user:item.operUser,
            oper_time:item.operTime,
          }));
          this.historyVisible = true;
        }else{
          this.$message.error('获取数据跟踪失败');
        }
      }).catch(error=>{
        this.$message.error('获取数据跟踪失败');
      })
    },

    /** 审核*/
    handleCheck(row) {
      if(row.status!=='2'){
        this.$message.warning('该数据已完成审核');
        return;
      }
      this.checkReview.status = row.status;
      this.checkReview.remark = row.remark;
      this.checkReview.visible = true;
      this.checkReview.row = row;

      // 记录修改前的数据
      this.data_name=row.dataName;
      this.oper_type='审核';
      this.log_before={
        "状态":statusMap[row.status],
        "备注":row.remark
      };

    },
    // 提交审核
    submitCheckReview() {
      const id = this.checkReview.row.id;
      const newStatus = this.checkReview.status.toString();
      const remark = this.checkReview.remark;
      auditDataFileStatus(id, newStatus, remark).then(response => {
        if (response.code === 200) {
          /**
           * 插入数据操作日志------------------
           */
          this.log_after={
            "状态":statusMap[newStatus],
            "备注":remark
          };
          this.insertLog();

          this.$message.success("审核成功");
          this.checkReview.visible = false;
          this.queryDataList();

        } else {
          this.$message.error("审核失败");
        }
      });
    },
    /** 删除单个项 */
    async handleDelete(row,type) {
      if(type==='single') await this.$modal.confirm('是否确认删除名称为 "' + row.dataName + '" 的数据项？');
      /** 删除数据库表及服务器文件 */
      const response = await delDataFileById(row.id);
      if (response.code === 200) {
        this.$message.success('删除成功');
      } else {
        this.$message.error('删除失败');
      }
      /** 删除数据操作日志 */
      this.deleteLogByDataName(row.dataName);
      this.queryDataList();
    },
    /** 多选删除 */
    async handleDelete_many() {
      const toDeleteRows = this.selectedRows;
      if(toDeleteRows.length===0){
        this.$message.warning('请至少选择一行');
        return;
      }
      await this.$modal.confirm('是否确认删除选中所有的数据项？');
      for (const row of toDeleteRows) {
        try {
          await this.handleDelete(row,'many');
        } catch (error) {
          this.$message.error('删除过程中出现错误');
        }
      }
      // 在所有删除操作完成后更新数据列表
      this.queryDataList();
      this.$message.success('所有选中的行都已删除');
    },



    /**
     * 其他功能操作   ---------------------------
     */
    /** 操作日志相关*/
    // 插入数据操作日志
    insertLog(){
      const operUser=this.$store.state.user.name;
      const content = {};
      // 遍历 log_before
      for (const [key, beforeValue] of Object.entries(this.log_before)) {
        // log_after 有相同的键
        if (key in this.log_after) {
          content[key] = {
            'before': beforeValue,
            'after': this.log_after[key]
          };
        }
      }
      // 转换为 JSON 字符串
      const contentString = JSON.stringify(content);

      const data={
        operType:this.oper_type,
        dataName:this.data_name,
        content:contentString,
        operUser:operUser,
      };

      insertLogData(data).then(response=>{
        if(response.code===200){
          this.$message.success('跟踪成功');
        }else{
          this.$message.error('跟踪失败');
        }
      }).catch(error=>{
        this.$message.error('跟踪失败');
      })
    },
    // 删除数据操作日志 by dataName
    deleteLogByDataName(dataName){
      deleteDataOperLogByDataName(dataName).then(response=>{
        if(response.code===200){
          this.$message.success('跟踪数据删除成功');
        }else{
          this.$message.error('跟踪数据删除失败');
        }
      }).catch(error=>{
        this.$message.error('跟踪数据删除失败');
      })
    },


    /**
     * ------------------------------------------   以标准为中心 ----------------------------------
     */
    /** 匹配  indicatorName 来展示 Desc*/
    getMatchedDesc(indicatorName) {
      if (!indicatorName) return '';
      if (indicatorName.length<3) return '';


      // 提取前3个字母
      const prefix = indicatorName.substring(0, 3).toUpperCase();

      // 查找匹配的 desc
      for (const key in this.indicatorName_Desc_Map) {
        if (key.startsWith(prefix)) {
          return this.indicatorName_Desc_Map[key];
        }
      }
      // 如果没有匹配，返回 ''
      return '';
    },

    /** 获取 indicatorName:Desc */
    getIndicator_Name_Desc_Map(){
      getIndicatorName_DescMap().then(response=>{
        if(response.code===200){
          this.indicatorName_Desc_Map = response.data.reduce((acc, item) => {
            acc[item.indicatorName] = item.description;
            return acc;
          }, {});
        }else{
          this.$message.error('获取指标描述数据失败');
        }
      }).catch(error=>{
        this.$message.error('获取指标描述数据失败');
      })

    },


    /**  点击标准号进行跳转 */
    moveToStandardManager(row) {
      if (!row.standardCode || !row.organization) {
        this.$message.error('标准号或组织机构信息缺失');
        return;
      }
      this.$router.push({
        path: '/standardmanager',
        query: {
          // standardCode: standardCode
          row: row // 传递整个行数据
        }
      });
    },

    //  重置Info  ---- 很蠢的方法 VoV
    resetInfoStandard(){
      this.addNewStandard.baseDialogVisible=false;
      this.addNewStandard.ISODialogVisible=false;
      this.addNewStandard.IECDialogVisible=false;
      this.addNewStandard.baseInfo={
        standardCode:'',
        standardName:'',
        classificationCode:'',
        organization:'',
        remark:'',
      };
      this.addNewStandard.ISO={
        standardCode:'',
        title:'',
        content:'',
        part:'',
        abstract_:'',
        status:'',
        publicationDate:'',
        stage:'',
        edition:'',
        numberOfPages:'',
        technicalCommittee:'',
        ics:'',
        contribute:'',
      };
      this.addNewStandard.IEC={
        standardCode:'',
        title:'',
        abstract_: '',
        publicationType:'',
        publicationDate: '',
        edition:'',
        availableLanguages:'',
        TC_SC: '',
        ICS:'',
        pages:'',
        relatedPublications:'',
      };
    },
    /**  新增标准 */
    handleAdd_standard(){
      this.addNewStandard.baseDialogVisible=true;
    },
    // 确定基本 的信息正确
    confirmBaseInfo(){
      if(this.addNewStandard.baseInfo.standardCode===''){
        this.$message.warning('请填写标准号');
        return;
      }
      // 已经存在标准号
      if(this.UD_dialog.standardCodeList.includes(this.addNewStandard.baseInfo.standardCode)){
        this.$message.warning('标准号已存在，请检查');
        return;
      }
      if(this.addNewStandard.baseInfo.standardName===''){
        this.$message.warning('请填写标准名称');
        return;
      }
      if(this.addNewStandard.baseInfo.classificationCode===''){
        this.$message.warning('请填写国际分类号');
        return;
      }
      if(this.addNewStandard.baseInfo.organization===''){
        this.$message.warning('请选择制定组织');
        return;
      }
      if(this.addNewStandard.baseInfo.remark===''){
        this.$message.warning('请填写备注');
        return;
      }
      if(this.addNewStandard.baseInfo.organization==='ISO'){
        this.addNewStandard.baseDialogVisible=false;
        this.addNewStandard.ISO.standardCode=this.addNewStandard.baseInfo.standardCode;
        this.addNewStandard.ISODialogVisible=true;
      }else if(this.addNewStandard.baseInfo.organization==='IEC') {
        this.addNewStandard.baseDialogVisible = false;
        this.addNewStandard.IEC.standardCode = this.addNewStandard.baseInfo.standardCode;
        this.addNewStandard.IECDialogVisible = true;
      }
    },
    // 确定ISO 格式正确
    confirmISOInfo(){
      if(Object.values(this.addNewStandard.ISO).includes('')){
        this.$message.warning('有未填写的信息，请检查');
        return false;
      }
      /** 检测contribute 格式是否正确*/
      try {
        JSON.parse(this.addNewStandard.ISO.contribute);
      } catch (e) {
        this.$message.warning('贡献记录 格式不正确，请检查');
        return false;
      }
      return true;
    },
    // 确定IEC 格式正确
    confirmIECInfo(){
      if(Object.values(this.addNewStandard.IEC).includes('')){
        this.$message.warning('有未填写的信息，请检查');
        return false;
      }
      /** 检测contribute 格式是否正确*/
      try {
        JSON.parse(this.addNewStandard.IEC.relatedPublications);
      } catch (e) {
        this.$message.warning('相关出版物 格式不正确，请检查');
        return false;
      }
      return  true;
    },

    // 确定ISO/IEC/... 具体信息
    async confirmInfo(type){
      await this.getStandardCodeList();
      if(type==='base')this.confirmBaseInfo();
      else if(type==='ISO'){
        // 检查ISO 格式
        if(!this.confirmISOInfo())return;
        await this.uploadStandardToDB('base');
        await this.uploadStandardToDB('ISO');
        this.addNewStandard.ISODialogVisible=false;
        this.resetInfoStandard();
      }else if(type==='IEC'){
        // 检查IEC 格式
        if(!this.confirmIECInfo())return;
        await this.uploadStandardToDB('base');
        await this.uploadStandardToDB('IEC');
        this.addNewStandard.IECDialogVisible=false;
        this.resetInfoStandard();
      }
      this.queryStandardList();
    },
    // 添加到数据库
    async uploadStandardToDB(type){
      if(type==='base'){
        /** 把 baseInfo 存到 standard表里*/
        addStandardBase(this.addNewStandard.baseInfo).then(response=>{
          if(response.code===200){
            this.$message.success('基本信息添加成功');
          }else{
            this.$message.error('基本信息添加失败');
          }
        }).catch(error=>{
          this.$message.error('基本信息添加失败');
        });
      }else if(type==='ISO'){
        /** 把 ISOInfo 存到 standard_iso 里面*/
        addStandardISO(this.addNewStandard.ISO).then(response=>{
          if(response.code===200){
            this.$message.success('ISO信息添加成功');
          }else{
            this.$message.error('ISO信息添加失败');
          }
        }).catch(error=>{
          this.$message.error('ISO信息添加失败');
        });
      }else if(type==='IEC'){
        /** 把 IECInfo 存到 standard_iec 里面*/
        addStandardIEC(this.addNewStandard.IEC).then(response=>{
          if(response.code===200){
            this.$message.success('IEC信息添加成功');
          }else{
            this.$message.error('IEC信息添加失败');
          }
        }).catch(error=>{
          this.$message.error('IEC信息添加失败');
        });
      }else {
        this.$message.error('未知标准类型，请检查');
      }
    },

    /**
     * 搜索-----------------
     */
    // 重置
    resetQuery_standard() {
      this.dateRange_standard = [];
      this.resetForm("queryForm_standard");
      this.handleQuery_standard();
    },

    //  搜索 --- 标准 --- 搜索第一页
    handleQuery_standard() {
      this.queryParams_standard.pageNum = 1;
      this.queryStandardList();
    },

    // 条件搜索
    queryStandardList(){
      this.loading_standard=true
      listStandard(this.addDateRange(this.queryParams_standard, this.dateRange_standard)).then(response => {
        this.standardList = response.rows;
        this.standardTotal = response.total;
        this.loading_standard = false;
      });
    },
    /**
     *  每行按钮操作---------------------------
     */
    /** 修改 --- 选择修改对象*/
    beforeHandleUpdate(row){
      this.BS_params.updateDialogVisible=true;
      this.BS_params.row=row;
    },
    /** 查看 --- 选择查看对象*/
    beforeHandleView(row){
      this.BS_params.viewDialogVisible=true;
      this.BS_params.row=row;
    },




    // 查看标准补充性文件
    viewSupplementFiles(row){
      this.BS_params.viewDialogVisible=false;

      mergeFilesPath(row.standardCode).then(response=>{
        if(response.code===200){
          this.BS_params.standardCode=row.standardCode;
          this.BS_params.filesPath=response.data;
          this.BS_params.supplementFilesVisible=true;
        }else{
          this.$message.error('获取补充性文件失败');
        }
      }).catch(error=>{
        this.$message.error('获取补充性文件失败');
      })
    },
    /** 修改标准 */
    async handleUpdate_standard(row) {
      this.BS_params.updateDialogVisible=false;
      // !!!!!!  把 StandardCode  转为 json 字符串再发送，不然可能会造成路径上的错误
      const jsonCode = JSON.stringify({standardCode:row.standardCode,organization:row.organization});
      const response = await getStandardDetailByCode(jsonCode);
      if(response.code===200 && response.data){
        this.data_to_edit =response.data
        this.detailVisible_edit=true;
        this.standardCode_to_edit=row.standardCode; // 记录当前待修改的标准号
      }else{
        this.$message.error('获取标准具体信息失败');
      }
    },
    async confirmUpdate_standard(){
      // 就是说，当点击确定后，这里的数据 data_to_edit应该是已经修改过的数据(标准具体信息)
      const data = JSON.stringify(this.data_to_edit);
      // 发送请求
      updateStandardDetailByCode(data).then(response=>{
        if(response.code===200){
          this.$message.success('修改成功');
          this.detailVisible_edit=false;
          this.queryStandardList();
        }else{
          this.$message.error('修改失败');
        }
      }).catch(error=>{
        this.$message.error('修改失败',error);
      })
    },
    /** 查看标准*/
    async handleView_standard(row){
      this.BS_params.viewDialogVisible=false;
      // !!!!!!  把 StandardCode  转为 json 字符串再发送，不然可能会造成路径上的错误
      const jsonCode = JSON.stringify({standardCode:row.standardCode,organization:row.organization});
      const response = await getStandardDetailByCode(jsonCode);
      if (response.code === 200 && response.data) {
        const {id,...detail}=response.data;
        this.data_to_show =detail;
        this.detailVisible_query=true;
      } else {
        this.$message.error('获取标准具体信息失败');
      }
    },
    /** 修改指标*/
    async handleUpdate_indicator(row) {
      this.BS_params.updateDialogVisible=false;
      await this.getExcelData(row.standardCode,'update');
    },
    async confirmUpdate_indicator(){
      const excelData = this.excel_to_show;

      const data = JSON.parse(JSON.stringify(excelData));
      // 发送修改请求
      updateExcelByStandardCode(data).then(response => {
        if (response.code === 200) {
          this.$message.success('修改成功');
          this.indicatorVisible_edit = false;
          this.queryStandardList();
        } else {
          this.$message.error('修改失败');
        }
      });

    },
    /** 查看指标*/
    async handleView_indicator(row){
      this.BS_params.viewDialogVisible=false;
      await this.getExcelData(row.standardCode,'view');
    },
    async getExcelData(standardCode,type){
      // !!!!!!  把 StandardCode  转为 json 字符串再发送，不然可能会造成路径上的错误
      const jsonCode = JSON.stringify({standardCode:standardCode});
      const response = await getStandardExcelByStandardCode(jsonCode);
      if (response.code === 200 && response.data) {
        const {remark,createBy,createTime,updateBy,updateTime,...detail}=response.data;
        this.excel_to_show=detail;
        if(type==='view'){this.indicatorVisible_query = true;}
        else if(type==='update'){this.indicatorVisible_edit = true;}
      } else {
        this.$message.error('暂无标准号为 '+standardCode+' 的指标得分数据');
      }
    },
    /** 删除标准*/
    /** 删除单个项 */

    async handleDelete_standard(row,type) {
      if(type==='single')await this.$modal.confirm('是否确认删除名称为"' + row.standardCode + '标准?');
      /** 删除数据库表及服务器文件 */
      const jsonCode = JSON.stringify({standardCode:row.standardCode,organization:row.organization});
      const response = await deleteStandardByCode(jsonCode);
      if (response.code === 200) {
        this.$message.success('删除成功');
      } else {
        this.$message.error('删除失败');
      }
      this.queryStandardList();
    },

    /** 多选删除标准 */
    async handleDelete_many_standard() {
      const toDeleteRows = this.selectedRows;
      if(toDeleteRows.length===0){
        this.$message.warning('请至少选择一行');
        return;
      }
      await this.$modal.confirm('是否确认删除选中所有的标准项？');
      for (const row of toDeleteRows) {
        try {
          await this.handleDelete_standard(row,'many');
        } catch (error) {
          this.$message.error('删除过程中出现错误');
        }
      }
      // 在所有删除操作完成后更新数据列表
      this.queryStandardList();
      this.$message.success('所有选中的行都已删除');
    },



    /** new ---end------------------------------------------------------------------------*/
    //标签页切换
    // handleTabClick(tab) {
    //   console.log('Tab clicked:', tab);
    // },
    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    /** 获取状态 */
    getStatusTagType(status) {
      if (status === '审核通过') {
        return 'success';
      } else if (status === '审核失败') {
        return 'danger';
      } else if (status === '待审核') {
        return 'warning';
      } else {
        return 'info';
      }
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      listMenu(this.queryParams).then(response => {
        this.menuList = this.handleTree(response.data, "menuId");
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu().then(response => {
        this.menuOptions = [];
        const menu = { menuId: 0, menuName: '主类目', children: [] };
        menu.children = this.handleTree(response.data, "menuId");
        this.menuOptions.push(menu);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,
        icon: undefined,
        menuType: "M",
        orderNum: undefined,
        isFrame: "1",
        isCache: "0",
        visible: "0",
        status: "0"
      };
      this.resetForm("form");
    },



    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.menuId) {
        this.form.parentId = row.menuId;
      } else {
        this.form.parentId = 0;
      }
      this.isAddDialogOpen = true;
      this.title = "添加菜单";
    },
    handleSelectChange(val) {
      if (val == '标准文件'){
        this.addDataFields=['数据名称']
      }else{
        this.addDataFields=['数据名称','标准名称']
      }
    },



    /** 跟踪操作 */
    handlePath2(row){
      this.reset();
      this.getTreeselect();
      getMenu(row.id).then(response => {
        this.form = response.data;
        this.isPathDialogOpen2 = true;
        this.title = "";
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getMenu(row.id).then(response => {
        this.form = response.data;
        this.isUpdateDialogOpen = true;
        this.title = "修改菜单";
      });
    },


    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.menuId != undefined) {
            updateMenu(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMenu(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
      // TODO:新增操作记录日志
      // TODO:修改操作记录日志

    },


  },

};
</script>

<style scoped>

</style>
